package com.binance.notification.web.push;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.connection.IHttpClient;
import cn.jiguang.common.resp.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ApacheHttpClient {

    private final static Object syncLock = new Object();
    private static CloseableHttpClient _httpClient = null;
    private final int _connectionTimeout;// 连接建立时间，三次握手完成时间，默认5s
    private final int _connectionRequestTimeout;// 这个时间就是从连接池获取连接的超时时间，默认10s
    private final int _socketTimeout;// 数据传输处理时间，默认10s
    private final int _maxRetryTimes;
    private String _authCode;
    private HttpHost _proxy;

    public ApacheHttpClient(String authCode, HttpProxy proxy, ClientConfig config) {
        _maxRetryTimes = config.getMaxRetryTimes();
        _connectionTimeout = config.getConnectionTimeout();
        _connectionRequestTimeout = config.getConnectionRequestTimeout();
        _socketTimeout = config.getSocketTimeout();
        _authCode = authCode;
        if (proxy != null) {
            _proxy = new HttpHost(proxy.getHost(), proxy.getPort());
        }
    }

    private CloseableHttpClient getHttpClient(String url) {
        String hostname = url.split("/")[2];
        int port = 80;
        if (hostname.contains(":")) {
            String[] arr = hostname.split(":");
            hostname = arr[0];
            port = Integer.parseInt(arr[1]);
        }
        if (_httpClient == null) {
            synchronized (syncLock) {
                if (_httpClient == null) {
                    _httpClient = createHttpClient(5000, 5000, 5000, hostname, port);
                    // _httpClient = createHttpClient(500, 100, 300, hostname, port);
                }
            }
        }
        return _httpClient;

    }

    public CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname,
            int port) {
        int timeout = 60;
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslsf).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        // 将最大连接数增加
        cm.setMaxTotal(maxTotal);
        // 将每个路由基础的连接增加
        cm.setDefaultMaxPerRoute(maxPerRoute);
        HttpHost httpHost = new HttpHost(hostname, port);
        // 将目标主机的最大连接数增加
        cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);

        cm.setValidateAfterInactivity(1000);

        // 请求重试处理
        HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= _maxRetryTimes) {
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接，那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return false;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// SSL握手异常
                    return false;
                }

                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的，就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };

        RequestConfig requestConfig = null;
        if (_proxy != null) {
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(_connectionRequestTimeout)
                    .setConnectTimeout(_connectionTimeout).setSocketTimeout(_socketTimeout)
                    .setExpectContinueEnabled(true).setProxy(_proxy).build();
        } else {
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(_connectionRequestTimeout)
                    .setConnectTimeout(_connectionTimeout).setSocketTimeout(_socketTimeout)
                    .setExpectContinueEnabled(true).build();
        }

        ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {

            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                long keepAlive = super.getKeepAliveDuration(response, context);
                return keepAlive <= 0 ? timeout * 1000 : keepAlive;
            }

        };

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setRetryHandler(
                httpRequestRetryHandler)/* .setConnectionTimeToLive(timeout, TimeUnit.SECONDS) */
                .evictExpiredConnections().evictIdleConnections(timeout / 2, TimeUnit.SECONDS)
                .setDefaultRequestConfig(requestConfig).setKeepAliveStrategy(keepAliveStrategy).build();

        return httpClient;
    }

    public ResponseWrapper sendPost(String url, String content) {
        ResponseWrapper wrapper = new ResponseWrapper();
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            // httpPost.setProtocolVersion(HttpVersion.HTTP_1_1); //默认已经是HTTP/1.1
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, _authCode);
            httpPost.setHeader("Content-Type", "application/json");
            StringEntity params = new StringEntity(content, IHttpClient.CHARSET);
            httpPost.setEntity(params);
            response = getHttpClient(url).execute(httpPost, HttpClientContext.create());
            log.info("推送信息到极光私有云请求正常返回...");
        } catch (SocketTimeoutException e) {
            log.warn("推送消息{}到极光私有云等待响应超时：{}", content, parseExceptionAsString(e));
        } catch (ConnectTimeoutException e) {
            log.error("推送消息{}到极光私有云请求超时：{}", content, e);
        } catch (IOException e) {
            log.error("推送消息{}到极光私有云出现异常：{}", content, e);
        } finally {
            HttpResponseParser.parser(response, wrapper, content);
            // try {
            // if (response != null) {
            // response.close();
            // }
            // } catch (IOException e) {
            // e.printStackTrace();
            // }
        }
        return wrapper;
    }

    private static String parseExceptionAsString(Exception e) {
        StringBuilder sb = new StringBuilder();
        sb.append(e.getClass().getName());
        sb.append(":");
        sb.append(e.getMessage());
        sb.append("\n");
        StackTraceElement[] stes = e.getStackTrace();
        for (StackTraceElement ste : stes) {
            sb.append("\tat ");
            sb.append(ste.toString());
            sb.append("\n");
        }
        return sb.toString();
    }

}
